package com.gavindon.android.view.search

import android.graphics.Color
import android.os.Bundle
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.leanback.widget.VerticalGridView
import com.gavindon.android.R
import com.gavindon.android.adapters.KeyBordAdapter
import com.gavindon.android.adapters.SearchRankingAdapter
import com.gavindon.android.adapters.SearchResultAdapter
import com.gavindon.android.base.BaseActivity
import com.gavindon.android.entity.HotTagResult
import com.gavindon.android.entity.SearchResp
import com.gavindon.android.network.DataResult
import com.gavindon.android.utils.click
import com.gavindon.android.utils.clickForResult
import com.gavindon.android.utils.toFullVideoOrDetailPage
import com.gavindon.android.viewmodel.SearchViewModel
import com.gavindon.android.widget.FocusViewUtils
import com.google.android.flexbox.FlexboxLayout
import org.jetbrains.anko.dip
import org.jetbrains.anko.toast
import org.jetbrains.anko.wrapContent

class SearchActivity : BaseActivity() {
    override val layoutId: Int = R.layout.activity_search

    private lateinit var keyboardRv: VerticalGridView
    private lateinit var keyboardAdapter: KeyBordAdapter
    private lateinit var searchView: LinearLayout
    private lateinit var searchEditText: EditText
    private lateinit var hotFlexLayout: FlexboxLayout
    private lateinit var rankingRv: VerticalGridView
    private lateinit var searchResultRV: VerticalGridView
    private lateinit var cslHotInfo: ConstraintLayout
    private lateinit var mViewModel: SearchViewModel
    private lateinit var llSearch: LinearLayout
    private lateinit var llClear: LinearLayout
    private lateinit var llDelete: LinearLayout
    private val inputStringBuilder = StringBuilder()

    private val rankingAdapter = SearchRankingAdapter(R.layout.adapter_ranking, null)
    private val searchResultAdapter = SearchResultAdapter(R.layout.adapter_banner_item, null)

    override fun onInit(savedInstanceState: Bundle?) {
        mViewModel = getViewModel()
        keyboardRv = findViewById(R.id.gridview_keybord)
        searchView = findViewById(R.id.search_view)
        searchEditText = findViewById(R.id.search_edit_text)
        hotFlexLayout = findViewById(R.id.flex_hot)
        rankingRv = findViewById(R.id.gridview_search_sort)
        llSearch = findViewById(R.id.ll_search)
        llClear = findViewById(R.id.ll_clear_input)
        cslHotInfo = findViewById(R.id.csl_hot)
        llDelete = findViewById(R.id.ll_delete)
        searchResultRV = findViewById(R.id.gridview_search_result)
        keyboardRv.setNumColumns(6)
        keyboardRv.setItemSpacing(30)
        keyboardRv.setGravity(Gravity.CENTER)
        val keyboardLst = mutableListOf(
            "A",
            "B",
            "C",
            "D",
            "E",
            "F",
            "G",
            "H",
            "I",
            "J",
            "K",
            "L",
            "M",
            "N",
            "O",
            "P",
            "Q",
            "R",
            "S",
            "T",
            "U",
            "V",
            "W",
            "X",
            "Y",
            "Z",
            "1",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9",
            "0"
        )
        keyboardAdapter = KeyBordAdapter(R.layout.adapter_keybord, keyboardLst)
        keyboardRv.adapter = keyboardAdapter

        keyboardAdapter.setOnItemClickListener { adapter, v, position ->
            inputStringBuilder.append(adapter.getItem(position).toString())
            searchEditText.setText(inputStringBuilder.toString())
        }
        FocusViewUtils.scaleView(llSearch, 1)
        FocusViewUtils.scaleView(llClear, 1)
        FocusViewUtils.scaleView(llDelete, 1)
        keyboardAdapter.setRightOrDownFocusChanged {
            if (it == 0) {
                if (cslHotInfo.visibility == View.VISIBLE) {
                    hotFlexLayout.requestFocus()
                } else {
                    searchResultRV.requestFocus()
                }
            } else {
                llSearch.requestFocus()
            }
        }
        llSearch.click {
            if (inputStringBuilder.toString().isNotEmpty()) {
                goSearch(inputStringBuilder.toString())
            } else {
                toast("请输入要搜索内容的拼音首字母")
            }
        }
        llDelete.setOnClickListener {
            val currentInputLength = inputStringBuilder.length
            if (currentInputLength > 0) {
                inputStringBuilder.deleteAt(currentInputLength - 1)
                searchEditText.setText(inputStringBuilder.toString())
            }
        }
        llClear.setOnClickListener {
            inputStringBuilder.clear()
            searchEditText.setText("")
        }

        initRanking()
        fetchRakingData()
    }

    private fun initHot(data: List<HotTagResult>) {
        hotFlexLayout.removeAllViews()
        for (i in data) {
            val textView = TextView(this)
            //先设置一个params 否则获取marginParams会空指针
            textView.layoutParams = LinearLayout.LayoutParams(wrapContent, wrapContent)
            textView.setPadding(20, 10, 20, 10)
            val lp = textView.layoutParams as ViewGroup.MarginLayoutParams
            lp.marginEnd = dip(18)
            lp.topMargin = dip(20)
            textView.text = i.name
            textView.isFocusable = true
            textView.setTextColor(Color.parseColor("#e6f1f1f1"))
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
            textView.layoutParams = lp
            textView.setBackgroundResource(R.drawable.full_sel)
            hotFlexLayout.addView(textView)
            textView.setOnClickListener {
                goSearch(word = i.name)
            }
        }
//        hotFlexLayout.setOnKeyListener { v, keyCode, event ->
//            rankingAdapter.recyclerView.layoutManager?.scrollToPosition(0)
//            return@setOnKeyListener false
//        }
    }

    /**
     * 搜索排行
     */
    private fun initRanking() {
        rankingRv.setNumColumns(3)
        rankingRv.setItemSpacing(dip(20))
        rankingRv.adapter = rankingAdapter
        searchResultRV.setNumColumns(3)
        searchResultRV.setItemSpacing(dip(20))
        searchResultRV.adapter = searchResultAdapter
    }


    private fun fetchRakingData() {
        mViewModel.getHotSearch().observe(this) {
            if (it is DataResult.Success) {
                initHot(it.data)
            }
        }
        mViewModel.getSearchRaking().observe(this) {
            if (it is DataResult.Empty) {
                rankingRv.setNumColumns(1)
                val empty = layoutInflater.inflate(R.layout.rv_empyt, null, false)
                rankingAdapter.setEmptyView(empty)
            } else if (it is DataResult.Success) {
                rankingRv.setNumColumns(3)
                rankingAdapter.setList(it.data.toMutableList())
            }
        }
    }

    private fun goSearch(pinyin: String = "", word: String = "") {
        toggleUi(true)
        mViewModel.getSearchResult(pinyin, word).observe(this) {
            if (it is DataResult.Success) {
                searchResultRV.setNumColumns(3)
                searchResultAdapter.setList(it.data.toMutableList())
                searchResultRV.requestFocus()
            } else if (it is DataResult.Empty) {
                searchResultAdapter.setList(null)
                searchResultRV.setNumColumns(1)
                searchResultAdapter.setEmptyView(R.layout.rv_empyt)
            }
        }
        searchResultAdapter.setOnItemClickListener { adapter, _, position ->
            val data = adapter.getItem(position) as SearchResp
            this.toFullVideoOrDetailPage(data.subjectType, data.courseId, data.courseName)
        }
    }

    override fun onBackPressed() {
        if (searchResultRV.visibility == View.GONE) {
            super.onBackPressed()
        } else {
            toggleUi(false)
        }
    }

    /**
     * @param showResult 是否是展示搜索结果的布局
     */
    private fun toggleUi(showResult: Boolean = false) {
        cslHotInfo.visibility = if (showResult) View.GONE else View.VISIBLE
        searchResultRV.visibility = if (!showResult) View.GONE else View.VISIBLE
    }

}